$(function() {
	createMakeRPButtons();
	createRetreatButtons()
});

function createRetreatButtons() {
	var planetLinks = $('a[href^=Planetfloats]:has(font[size=3])');
	
	planetLinks.each(function() {
		var planetId = this.href.match(/[0-9]{1,}$/)[0]
		
		$( document.createElement('a') )
			.html("Retreat")
			.addClass('rpButton')
			.insertBefore( this )
			.data('planetId', planetId )
			.click( retreatButton_click )
		;
	});
}

function createMakeRPButtons() {
	var planetLinks = $('a[href^=Planetfloats]:has(font[size=3])');
	
	var currentRP = getCookie("RP");
	
	planetLinks.each(function() {
		var planetName = $('font[size=3]',this).html()
		var planetId = this.href.match(/[0-9]{1,}$/)[0]
		
		$( document.createElement('a') )
			.html("Set RP")
			.addClass('rpButton')
			.insertBefore( this )
			.data('planetName', planetName )
			.data('planetId', planetId )
			.click( setRPButton_click )
		;
		
		if( currentRP && currentRP == planetName ) {
			//Mark this planet as the RP
			markAsRP(this);
		}
	});
}

function markAsRP(planetLink) {
	if( !$('#rpMarker').length )
		$( document.createElement('span') )
			.addClass('rpMarker')
			.html('(RP)')
			.attr('id', 'rpMarker')
			.insertBefore( $(planetLink).closest('td').find('font:last') )
		;
	else
		$('#rpMarker').insertBefore( $(planetLink).closest('td').find('font:last') )
}

function setRPButton_click(e) {
	var c = getCaller(e)
	
	setCookie('RP', $(c).data('planetName'), 365)
	setCookie('RPID', $(c).data('planetId'), 365)
	
	markAsRP(c)
}



function retreatButton_click(e) {
	var currentRP = getCookie("RP")
	var currentRPID = getCookie("RPID")
	
	if( !currentRP ) {
		alert('NO RP!')
		return
	}
	
	var c = getCaller(e);
	var planetPage = siteBase + "servlet/Planetfloats?planetid=";
	var planetId = $(c).data('planetId');
	
	captchaAwareAjax({
		url: planetPage + planetId,
		success: function(xhr, statusText) {
			var armyForm = xhr.match(/<form[^>]*name=['"]*armylist[^>]*>.*?<\/form>/);
			
			if( armyForm ) {
				//Load as much GA as possible
				loadArmies( armyForm[0],  xhr, currentRP, currentRPID, planetId, function() {
					$(c).trigger('click');
				});
			} else {
				retreatFleet(  xhr, currentRP, currentRPID, planetId, function() {
					$(c).html('RETREATED!');
				});
			}
		}
	})
}

function loadArmies(armyForm, xhr, currentRP, currentRPID, planetId, callback, index ) {
	if( !index ) index = 0;

	var fleetBoxes = armyForm.match(new RegExp("<[^>]+name=army[^>]*?"+index+"[^>]+>", 'g') );

	if( !fleetBoxes || fleetBoxes.length != 4 ) {
		return callback();
	}
	
	var formData = {
		army0 : fleetBoxes[0].match(/value=([0-9]+)/)[1],
		armyname0 : fleetBoxes[1].match(/value="([^">]+)/)[1],
		armysize0 : fleetBoxes[2].match(/value=([0-9]+)/)[1],
		armyrace0 : fleetBoxes[3].match(/value=([0-9]+)/)[1],
		loadarmies : "Load",
		iscamouflage : armyForm.match(/<[^>]+iscamouflage[^>]+>/)[0].match(/value=([0-1])/)[1],
		planetid: planetId,
		nbarmies: 1,
		isownplanet : armyForm.match(/<[^>]+isownplanet[^>]+>/)[0].match(/value=([0-1])/)[1]
	};
	
	captchaAwareAjax({
		url: siteBase + "servlet/Floatorders",
		data: formData,
		type: "POST",
		success: function(loadPage, statusText) {
			var fleetCaps = loadPage.match(/(<[^<]+)([0-9]+)(?=<\/option>)/gi);
			var fleetId;
			var fleetSize = 0;
			var tmpSize;
			var armySize = formData.armysize0*1;
			
			for( var fleetIdx = 0; fleetIdx < fleetCaps.length; fleetIdx++ ) {
				//Get the fleet capacity and then turn it into an int
				tmpSize = ( fleetCaps[fleetIdx].match(/[0-9]+$/)[0] ) * 1;
				if( tmpSize > fleetSize ) {
					fleetSize = tmpSize;
					fleetId = fleetCaps[fleetIdx].match(/value=([0-9]+)/)[1];
				}
			}
			
			if( armySize < fleetSize ) armySize = fleetSize;
			
			var armyFormData = {
				armysize0 : formData.armysize0,
				army0 : formData.army0,
				initarmysize0 : formData.armysize0,
				fleetid0 : fleetId,
				loadarmies : "Load Armies",
				planetid : formData.planetid,
				mgt_order_done : "",
				nbarmies : 1
			}
			
			captchaAwareAjax({
				url: siteBase + "servlet/Floatorders",
				data: armyFormData,
				type: "POST",
				success: function(loadSuccessPage, statusText) {
					index++;
					loadArmies(armyForm, xhr, currentRP, currentRPID, planetId, callback, index);
				}
			});
		}
	});
}

function retreatFleet( xhr, currentRP, currentRPID, planetId, callback ) {
	var fleetCheckboxes = xhr.match(/<input type=checkbox [^>]*?(name=fleet){1,}?[^>]*?>/g);
	var camoIdent = xhr.match( /<[^<]*camouflage_fleets[^>]*><option[^>]*(.)>/ );
	var camo = 1;
	
	if( camoIdent && camoIdent.length > 1 ) {
		camo = camoIdent[1]*1;
	}
	
	var formData = {
		targetname : currentRP,
		targetid : currentRPID,
		planetid : planetId,
		movefleets : "Launch Fleet",
		mission : 1,
		mgt_order_done : "",
		launch : "",
		camouflage : camo
	};
		
	if( !fleetCheckboxes ) {
		alert('No fleets to retreat!');
		if( callback ) callback();
		return
	}
		
	var inpName;
	var inpVal;
	$(fleetCheckboxes).each(function() {
		inpName = this.toString().match(/name=[^\s>]{1,}/)[0].replace(/name=/,'');
		inpVal = this.toString().match(/value=[^\s>]{1,}/)[0].replace(/value=/,'');
		
		formData[inpName] = inpVal;
	});
	
	formData.nbfleets = fleetCheckboxes.length;
		
	captchaAwareAjax({
		url: siteBase + "servlet/Floatorders",
		data: formData,
		type: "POST",
		success: function(xhr, statusText) {
			if( callback ) callback();
		}
	})
}